package cn.qidisoft.edu.hzjt.controller.zyc;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

import cn.qidisoft.core.common.context.ApplicationContextConfigUtil;
import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.file.FileUtil;
import cn.qidisoft.core.util.moffice.excel.ExpExcelUtil;
import cn.qidisoft.core.util.uuid.UUIDGenerator;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.exception.RPCException;
import cn.qidisoft.edu.hzjt.model.BjxxClassMaterialFile;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.model.zyc.TeacherThesis;
import cn.qidisoft.edu.hzjt.model.zyc.TeacherThesisAtt;
import cn.qidisoft.edu.hzjt.service.xb.IWindUpStudyService;
import cn.qidisoft.edu.hzjt.service.zyc.ITeacherThesisAttService;
import cn.qidisoft.edu.hzjt.service.zyc.ITeacherThesisService;
import cn.qidisoft.edu.hzjt.utils.LogType;

/***
 * 课题管理-论文审批
 */
@Controller
@RequestMapping(value = "teacherThesisAuditing")
public class TeacherThesisAuditingController {

	protected static final LoggerAdapter LOGGER =
			LoggerAdapterFactory.getLogger(LogType.HZJT_LOGGER.val);

	@Autowired
	ITeacherThesisService teacherThesisService;
	@Autowired
	ITeacherThesisAttService teacherThesisAttService;
	@Autowired
	private IWindUpStudyService service;

	private static String upload = null;

	static {
		upload = ApplicationContextConfigUtil.getString("file.path", null);
	}

	private static Map<String, List<TeacherThesisAtt>> picMap = new HashMap<>();

	@RequestMapping(value = "/index")
	public String index(ModelMap model, HttpServletRequest request) {
		request.setAttribute("msg", BaseController.getParameter("msg"));
		BaseController.removeParameter("msg");

		//获取部门list
		List<Map<String, Object>> deptList = service.queryAllDeptList();
		request.setAttribute("deptList", deptList);

		//获取组织list
		List<Map<String, Object>> orgList = service.queryAllOrgList();
		request.setAttribute("orgList", orgList);

		return "zyc/teacherThesisAuditing/teacherThesisAuditingList";
	}

	@RequestMapping(value = "/list")
	@ResponseBody
	public ResponseResult list(
			ModelMap model, HttpServletRequest request,
			@RequestParam(value = "rows", required = false) String pageSize,
			@RequestParam(value = "page", required = false) String currentPage,
			TeacherThesis data) {
		try {
			Map<String, Object> map = new HashMap<>();
			String ksId = request.getParameter("ksId");
			if (!StringUtils.isEmpty(ksId)) {
				map.put("ksId", ksId);
			}

			String tgId = request.getParameter("tgId");
			if (!StringUtils.isEmpty(tgId)) {
				map.put("tgId", tgId);
			}

			String empId = request.getParameter("empId");
			if (!StringUtils.isEmpty(empId)) {
				map.put("empId", empId);
			}

			String xm = request.getParameter("xm");
			if (!StringUtils.isEmpty(xm)) {
				map.put("xm", xm.trim());
			}

			String tjjg = request.getParameter("tjjg");
			if (!StringUtils.isEmpty(tjjg)) {
				map.put("tjjg", tjjg);
			}

			String subject = request.getParameter("subject");
			if (!StringUtils.isEmpty(subject)) {
				map.put("subject", subject);
			}


			String hjjb = request.getParameter("hjjb");
			if (!StringUtils.isEmpty(hjjb)) {
				map.put("hjjb", hjjb);
			}

			String startTime = request.getParameter("startTime");
			if (!StringUtils.isEmpty(startTime)) {
				map.put("startTime", startTime);
			}

			String endTime = request.getParameter("endTime");
			if (!StringUtils.isEmpty(endTime)) {
				map.put("endTime", endTime);
			}

			Page page = new Page();
			page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
			page.setPageSize(pageSize == null ? Constant.PageSize : Integer.valueOf(pageSize));

			BaseController.setSortByColumn(request, "createtime", "desc");
			map.put("orderField", (String) request.getAttribute("orderField"));
			map.put("orderFlag", (String) request.getAttribute("orderFlag"));

			PaginationBean<Map<String, Object>> paginationBean = teacherThesisService.queryUserAllAuditData(map, page);

			ResponseResult result = new ResponseResult();
			result.setTotal(paginationBean.getTotalRecords());
			result.setRows(paginationBean.getPageList());
			return result;
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
		return null;
	}

	@RequestMapping(value = "/addInInt", method = RequestMethod.GET)
	public String add(ModelMap model, HttpServletRequest request) {
		UserEmployee userEmployee =
				(UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String lwid = request.getParameter("lwid");
		// 查询论文提交人信息
		TeacherThesis teacherThesis = teacherThesisService.getBylwid(lwid);
		String today = dateFormat.format(new Date());
		Map<String, Object> reMap = new HashMap<>();
		reMap.put("createTime", today);
		reMap.put("creatorName", userEmployee.getXm());
		request.setAttribute("entity", reMap);
		request.setAttribute("teacherThesis", teacherThesis);
		request.setAttribute("msg", BaseController.getParameter("msg"));
		BaseController.removeParameter("msg");
		return "zyc/teacherThesisAuditing/teacherThesisAuditingAdd";
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(ModelMap model, HttpServletRequest request,
			TeacherThesis data) {
		try {
			UserEmployee userEmployee =
					(UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
			String action = request.getParameter("action")==null?"":request.getParameter("action");
			//data.setXkid(userEmployee.getEmid());
			data.setGid(UUIDGenerator.genReqID());
			data.setAuditorId(userEmployee.getUid());
			data.setAuditorName(userEmployee.getXm());
			data.setCreateTime(new Date());
			//	            teacherThesisService.insert(data);
			if(action.equals("1")) {
				data.setTjjg("推荐");
				teacherThesisService.update(data);
			}  else if(action.equals("2")) {
				data.setTjjg("不推荐");
				teacherThesisService.update(data);
			}

			BaseController.setParameter("msg", "提交成功");
			return "redirect:index";
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("添加信息 add [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}
	/**
	 * 设置推荐     不推荐
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/recommend", method = RequestMethod.POST)
	public String delete(ModelMap model, HttpServletRequest request) {
		try {
			String[] idList = request.getParameter("idList").split(",");
			String tJJG = null;
			String action = request.getParameter("action");
			if(action.equals("1")) {
				tJJG = "推荐";
			} else if(action.equals("2")) {
				tJJG = "不推荐";
			}
			teacherThesisService.updatetJJG(idList,tJJG);
			BaseController.setParameter("msg", "设置成功");
			return "redirect:index";
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("删除 delete [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}


	/**
	 * 新增删除
	 *
	 * @param file
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/source_upload", method = RequestMethod.POST)
	public @ResponseBody void loadFile(@RequestParam("file") MultipartFile file,
			HttpServletRequest request, HttpServletResponse response) {
		List<TeacherThesisAtt> list = new ArrayList<>();
		UserEmployee userEmployee = (UserEmployee) request.getSession()
				.getAttribute(Constant.LOGIN_CONSOLE_USER);
		List<TeacherThesisAtt> docFileResourceList = picMap
				.get(String.valueOf(userEmployee.getUserid()));
		// 本地env配置路径
		String path = upload;
		try {
			String gid = UUID.randomUUID().toString();
			String name = file.getOriginalFilename();// 获取上传文件名
			// 获取文件后缀名称
			String extend = FilenameUtils.getExtension(name);
			TeacherThesisAtt docFile = new TeacherThesisAtt();
			if (!file.isEmpty()) {
				// 文件的大小
				docFile.setFileSize(String.valueOf(FileUtil.FormetFileSize(Long.valueOf(file.getSize()))));
				docFile.setFileName(name);
				docFile.setFilePath(gid + File.separator + gid + "." + extend);
				docFile.setExtension(FileUtil.getFileExtendName(name).toLowerCase());
				docFile.setMufile(file);
				docFile.setInputStream(file.getInputStream());
				docFile.setSysfilepath(path + File.separator + gid + File.separator + gid + "." + extend);
				if (docFileResourceList != null && docFileResourceList.size() > 0) {
					docFileResourceList.add(docFile);
					picMap.put(String.valueOf(userEmployee.getUserid()), docFileResourceList);
				} else {
					list.add(docFile);
					picMap.put(String.valueOf(userEmployee.getUserid()), list);
				}
				LOGGER.info("附件上传成功！");
			}
			PrintWriter writer = null;
			BjxxClassMaterialFile docFile2 = new BjxxClassMaterialFile();
			docFile2.setFilepath(docFile.getFilePath());
			// 文件名称
			docFile2.setFilename(docFile.getFileName());
			docFile2.setSysfilepath(path + File.separator + gid + File.separator + gid + "." + extend);
			writer = response.getWriter();
			String json = JSONObject.toJSONString(docFile2);
			writer.write(json);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 论文审批下载
	 *
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "export_teacherThesisAuditing")
	public @ResponseBody void export_dzb(HttpServletRequest request, HttpServletResponse response,TeacherThesis data) throws Exception {
		try {
			Map<String, Object> queryMap = new HashMap<String, Object>();
			String begintime = request.getParameter("begintime");
			String endtime = request.getParameter("endtime");
			queryMap.put("TeacherThesis", data);
			queryMap.put("begintime", begintime);
			queryMap.put("endtime", endtime);
			queryMap.put("title", request.getParameter("subject"));
			queryMap.put("creatorname",request.getParameter("creatorName"));
			List<TeacherThesis> datalist = teacherThesisService.getLwspList(queryMap);
			String[][] title_name = { { "id", "姓名", "工号", "所在部门", "论文题目", "论文时间","推荐结果","获奖级别","提交时间"} };
			String[] title_style = { "hwzs_16_bold_25","hwzs_16_bold_25","hwzs_16_bold_25","hwzs_16_bold_25", "hwzs_16_bold_25",
					"hwzs_16_bold_25","hwzs_16_bold_25","hwzs_16_bold_25","hwzs_16_bold_25" };
			String fileName = "论文审批信息";
			String[] remark = { "" };
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			if (datalist != null && !datalist.isEmpty()) {
				for (TeacherThesis res : datalist) {
					Map<String, Object> map = new LinkedHashMap<String, Object>();
					map.put("lwid", res.getLwid());
					map.put("empId", res.getEmpId());
					map.put("empName", res.getEmpName());
					map.put("dZBMC", res.getEmpId());
					map.put("subject", res.getSubject());
					map.put("lwsj", res.getLwsj());
					map.put("tjjg", res.getTjjg());
					map.put("hjjb", res.getHjjb());
					map.put("createTime", res.getCreateTime());
					list.add(map);
				}
			}
			HSSFWorkbook wb = ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark, fileName, list);
			try {
				String filenameConvert = "论文审批信息";/* new String(fileName.getBytes("GB2312"), "ISO8859-1"); */
				response.reset();
				response.setContentType("application/vnd.ms-excel;charset=utf-8");
				response.setHeader("Content-Disposition",
						"attachment;filename=" + new String((filenameConvert + ".xls").getBytes(), "iso-8859-1"));
				response.setDateHeader("Expires", 0);
				ServletOutputStream os = response.getOutputStream();
				wb.write(os);
				os.flush();
			} catch (Exception e) {
				System.out.println("网络连接断开，可能用户取消了导出");
			}
		} catch (RPCException e) {
			LOGGER.error("获得xxxxx信息 exportStudentjobList [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
		}
	}




	/**
	 * 新增删除服务器的文件
	 *
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unused")
	@RequestMapping(value = "/deletefile", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> deleteFile(HttpServletRequest request) {

		Map<String, Object> dataMap = new HashMap<String, Object>();
		try {
			UserEmployee userEmployee = (UserEmployee) request.getSession()
					.getAttribute(Constant.LOGIN_CONSOLE_USER);
			// env配置路径
			String path = upload;
			String filepath = request.getParameter("filepath");
			LOGGER.info("文件的原始路径===" + filepath);
			// 文件的全路径
			String fullpath = null;
			// 文件名称
			String filename = null;
			// 文件名无后缀
			String fileNoSuffix = null;
			if (filepath.indexOf("prefix") == -1) {
				// 文件的文件名称
				fileNoSuffix = filepath.split(",")[0];
				String sec = filepath.split(",")[1];
				// 文件的后缀
				String suffix = sec.substring(sec.indexOf("."));
				// 文件名无后缀加上后缀
				filename = fileNoSuffix + suffix;
				// 文件的全路径
				fullpath = path + "/" + fileNoSuffix;
				// FileUtil.deleteFile(fullpath, filename);//删除文件目录下面的文件
				// FileUtils.forceDelete(new File(fullpath)); //删除文件目录
			} else {
				return dataMap;
			}
			List<TeacherThesisAtt> noticeNewsFilepathList = picMap
					.get(String.valueOf(userEmployee.getUserid()));
			// 删除list里面前台删除的前台信息图片附件表
			if (noticeNewsFilepathList != null && !noticeNewsFilepathList.isEmpty()) {
				for (TeacherThesisAtt obj : noticeNewsFilepathList) {
					if (obj.getFileName().equals(fileNoSuffix)) {
						noticeNewsFilepathList.remove(obj);
						break;
					}
				}
			}
			// 先删除
			picMap.remove(userEmployee.getUserid());
			// 后添加
			picMap.put(String.valueOf(userEmployee.getUserid()), noticeNewsFilepathList);
			dataMap.put("success", "0000");
			return dataMap;
		} catch (Exception e) {
			dataMap.put("success", "-9999");
			return dataMap;
		}
	}

}
